<?php
# +--------------------------------------------------------
# |Description: 阳光公采接口：商品处理类
# +--------------------------------------------------------
# |Company: 北京申合信科技发展有限公司
# +--------------------------------------------------------
# |WebSite: www.shenhexin.com
# +--------------------------------------------------------
# |Author: Akon<18363851918@163.com>
# +--------------------------------------------------------
# |Date: 2017年6月20日
# +--------------------------------------------------------

namespace Api\Controller;
use Think\Controller;

class ProductController extends Controller {
    
    /**
     * 获取品目池接口
     * URL http://api.shenhexin.com/api/product/get_pools
     * METHOD POST
     * 1、获取access_token
     * 2、校验access_token，若过期，则重新获取
     * 3、获取商品分类数据
     */
    public function get_pools(){
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);
        $cate_info = M('goods_cat','sdb_','DB_CONFIG2')->field('cat_name name,yggc_id id')->select();
        if(!$cate_info){
            $res = array(
                'success' => 'false',
                'desc' => '请检查输入是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        }

        $tempArr= array();
        foreach($cate_info as $key=>$val){
            if(empty($val[id])) continue;
            $tempArr[$key]['name'] = $val['name'];
            $tempArr[$key]['id'] = $val['id'];
        }
        $return_cate_info = array_values($tempArr);
        $res = array(
            'success' => 'true',
            'result'  => $return_cate_info
        );
        echo json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    /**
     * 获取商品编号SKU接口
     * URL http://api.shenhexin.com/api/product/skus
     * METHOD POST
     * 1、获取access_token,catalog_id
     * 2、校验access_token，若过期，则重新获取
     * 3、通过catalog_id获取商品sku
     */
    public function skus(){
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                                         //校验access_token是否合法
        A('Common')->errorMsg($receive['catalog_id'],'error catalog_id');                         //校验catalog_id是否合法
        /**
         * 分类规则：原则上传递过来的分类id为三级分类,但是也有个别的二级分类，所以要判断是否为二级分类
         */
        $cate_id = M('goods_cat','sdb_','DB_CONFIG2')->where(array('yggc_id'=>$receive['catalog_id']))->field('cat_id')->find();
        $is_third_cate = M('goods_cat','sdb_','DB_CONFIG2')->where(array('parent_id'=>$cate_id['cat_id']))->field('cat_id')->select();

        if(!$is_third_cate){      //三级分类
            $sku_info = M('goods','sdb_','DB_CONFIG2')->where(array('cat_id'=>$cate_id['cat_id']))->field('bn,intro,brand')->select();
        }else{                    //二级分类
            foreach($is_third_cate as $key=>$val){
                $cat_id_arr[$key] = $val['cat_id'];
            }
            $sql = "SELECT bn,intro,brand FROM sdb_goods WHERE cat_id IN (".implode(',',$cat_id_arr).")";
            $sku_info = M('goods','sdb_','DB_CONFIG2')->query($sql);
        }

        if(!$sku_info){
            $res = array(
                'success' => 'false',
                'desc' => '输入有误或此分类下没有商品'
            );
            exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        }

        $sku = array();

        foreach($sku_info as $key=>$value){
            $sku_info[$key]['intro'] = htmlspecialchars($value['intro']);
            if(strlen($sku_info[$key]['intro']) < 20) break;                                    //屏蔽掉没有详情图的商品sku
            if(empty($sku_info[$key]['brand'])) break;                                          //屏蔽掉没有品牌的商品sku
            $sku[] = $value['bn'];
        }

        $res = array(
            'success' => 'true',
            'result'  => $sku
        );
        echo json_encode($res,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 商品详情接口
     * URL http://api.shenhexin.com/api/product/detail
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token，若过期，则重新获取
     * 3、通过sku获取商品详情，只支持单个查询
     */
    public function detail(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                  //校验access_token是否合法
        A('Common')->errorMsg($receive['sku'],'error sku');                //校验sku是否合法

        $query      = "
                      SELECT a.goods_id,a.bn sku,a.weight,a.big_pic image_path,a.marketable state,a.brand brand_name,a.name,a.unit,b.cat_name category,a.intro introduction
                      FROM sdb_goods a
                      join sdb_goods_cat b
                      on a.cat_id=b.cat_id
                      where bn='{$receive['sku']}'";
        $detail_res = M('','','DB_CONFIG2')->query($query);

        if(!$detail_res){
            $res = array(
                'success' => 'false',
                'desc' => '请检查输入是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_SLASHES));
        }

        $details    = $detail_res[0];
        //处理数据
        $details['url']          = "http://www.shenhexin.com/?product-" . $details['goods_id'] . ".html";
        $intro = $detail_res[0]['introduction'];
        $details['introduction'] = $intro;
        $details['image_path']   = "http://www.shenhexin.com/".explode('|',$details['image_path'])[0];
        $details['model']        = "";
        $details['product_area'] = "";
        $details['upc']          = "";
        $details['service']      = "";
        $param = "<table class='Ptable'><tr><td class='tdTitle'>品牌</td><td>".$detail_res[0]['brand']."</td></tr><tr><td class='tdTitle'>商品名称</td>".$detail_res[0]['name']."</td></tr></table>";
        $details['param']        = $param;
        $details['ware']         = "";
        $details['sale_actives'] = 0;
        //if(empty($details['unit'])) $details['unit'] = '个';
        $details['unit'] = empty($details['unit']) ? '个' : $details['unit'];
        unset($details['goods_id']);
        $res = array(
            'success' => 'true',
            'result'  => $details
        );
        echo json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 上下架状态接口
     * URL http://api.shenhexin.com/api/product/shelf_states
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token，若过期，则重新获取
     * 3、通过sku获取上下架状态，支持批量查询，用","分隔
     */
    public function shelf_states(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                 //校验access_token是否合法
        A('Common')->errorMsg($receive['sku'],'error sku');                      //校验sku是否合法
        $skuStr = addApostropheToString($receive['sku']);                  //单个字符添加单引号

        $sql   = 'select bn sku,marketable state from sdb_goods where bn in ('."{$skuStr}".')';
        $states = M('','','DB_CONFIG2')->query($sql);

        if(!$states){
            $res = array(
                'success' => 'false',
                'desc' => '请检查输入是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        foreach($states as $key=>$val){
            if($val['state'] == 'true'){
                $states[$key]['state'] = 1;
            }else if($val['state'] == 'false'){
                $states[$key]['state'] = 0;
            }
        }
        $res = array(
            'success' => 'true',
            'result'  => $states
        );
        exit(json_encode($res,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 图片接口
     * URL http://api.shenhexin.com/api/product/images
     * METHOD POST
     * 1、获取access_token、sku
     * 2、校验access_token，若过期，则重新获取
     * 3、通过sku获取图片接口，支持批量查询，用","分隔
     */
    public function images(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                    //校验access_token是否合法
        A('Common')->errorMsg($receive['sku'],'error sku');                  //校验sku是否合法
        $sku_str = addApostropheToString($receive['sku']);             //单个字符添加单引号

        $get_id_sql   = 'SELECT goods_id
                         FROM sdb_goods
                         WHERE bn
                         IN ('.$sku_str.')';
        $get_sku_sql  = 'SELECT goods_id,bn sku
                         FROM sdb_goods
                         WHERE bn
                         IN ('.$sku_str.')';
        $goods_skus   = M('','','DB_CONFIG2')->query($get_sku_sql);
        $goods_ids    = M('','','DB_CONFIG2')->query($get_id_sql);

        if(!$goods_skus || !$goods_ids){
            $res = array(
                'success' => 'fail',
                'desc' => '请检查输入是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        $goods_id_str = implode(',',array_column($goods_ids,'goods_id'));
        $get_img_sql  = 'SELECT goods_id,big path,orderby
                         FROM sdb_gimages
                         WHERE goods_id
                         in ('.$goods_id_str.')';
        A('Common')->errorMsg($goods_skus,'no data');

        $goods_imgs      = M('','','DB_CONFIG2')->query($get_img_sql);
        $last_goods_imgs = array();
        foreach($goods_skus as $k=>$v){
            $last_goods_imgs[$v['goods_id']]['sku'] = $v['sku'];
        }
        foreach($goods_imgs as $key=>$val){
            $img = explode('|',$val['path']);
            $last_goods_imgs[$val['goods_id']]['images'][$key]['path']  = 'http://www.shenhexin.com/' . $img[0];
            $last_goods_imgs[$val['goods_id']]['images'][$key]['order'] = $val['orderby'];
        }
        foreach($last_goods_imgs as $key=>$val){
            $last_goods_imgs[$key]['images'] = array_values($val['images']);
        }
        $last_goods_imgs = array_values($last_goods_imgs);

        $res = array(
            'success' => 'true',
            'result'  => $last_goods_imgs
        );
        exit(json_encode($res,JSON_UNESCAPED_SLASHES));
    }

    /**
     * 价格接口
     * URL http://api.shenhexin.com/api/product/prices
     * METHOD POST
     * 1、获取access_token，sku
     * 2、校验access_token,若过期，则重新获取
     * 3、通过sku获取商品价格，sku支持批量，以逗号分隔
     */
    public function prices(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                    //校验access_token是否合法
        A('Common')->errorMsg($receive['sku'],'error sku');                  //校验sku是否合法
        $sku_str = addApostropheToString($receive['sku']);                   //单个字符添加单引号

        $sql = 'SELECT bn sku,price mall_price FROM sdb_goods WHERE bn IN ('.$sku_str.')';
        $goods_prices = M('','','DB_CONFIG2')->query($sql);

        if(!$goods_prices){
            $res = array(
                'success' => 'false',
                'desc' => '请检查输入是否正确'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        A('Common')->errorMsg($goods_prices,'no data');

        foreach($goods_prices as $key=>$val){
            $goods_prices[$key]['price'] = sprintf('%.2f',$val['mall_price'] * 0.95);
        }
        $res = array(
            'success' => 'true',
            'result'  => $goods_prices
        );
        $this->ajaxReturn($res);
    }

    /**
     * 库存接口
     * URL http://api.shenhexin.com/api/product/area/stocks
     * METHOD POST
     */
    public function stocks(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);
        A('Common')->errorMsg($receive['sku'],'请检查输入是否正确');
        A('Common')->errorMsg($receive['area'],'请检查输入是否正确');
        $sku_str = addApostropheToString($receive['sku']);                   //单个字符添加单引号

        $sql = "SELECT bn sku,IF(store>0,'有货','无货') as des,store num FROM sdb_goods WHERE bn IN (".$sku_str.")";
        $stocks = M('','','DB_CONFIG2')->query($sql);

        foreach($stocks as $key=>$val){
            $stocks[$key]['desc'] = $val['des'];
            $stocks[$key]['area'] = $receive['area'];
            unset($stocks[$key]['des']);
        }
        $res = array(
            'success' => 'true',
            'result'  => $stocks
        );
        exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }

}